<template>
  <div class="home-page" ref="homePage">
    <el-container>
      <!-- 顶栏 -->
      
      <el-header height="60px">
        <div>
          <!-- <span>菜单</span> -->
          <h2 @click="drawer = true">箱图</h2>
        </div>
      </el-header>

      <el-row>
     <el-button class="ImportButton" type="button" name="seach" @click="FuncCSVInportTwo">
            GRR Import
      </el-button>
      <el-button class="ImportButton" type="button" name="seach" @click="FuncCSVInport">
            CSV Import
      </el-button>
</el-row>





<el-drawer
  title="功能选择"
  :visible.sync="drawer"
  :direction="direction"
  :before-close="handleClose">
  <el-row class="tac">
  <el-col :span="24">
    <el-menu
      default-active="2"
      class="el-menu-vertical-demo"
      @open="handleOpen"
      @close="handleClose">
      <el-submenu index="1">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>声学</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="1-1" @click="clickMenu('1-1')">折线</el-menu-item>
          <el-menu-item index="1-2" @click="clickMenu('1-2')">cpk</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <el-submenu index="2">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>光学</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="2-1" @click="clickMenu('2-1')">箱图</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <!-- <el-submenu index="3">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>SMT</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="3-1" @click="clickMenu('3-1')">折线图</el-menu-item>
          <el-menu-item index="3-1" @click="clickMenu('3-2')">cpk</el-menu-item>
        </el-menu-item-group>
      </el-submenu> -->
    </el-menu>
  </el-col>
</el-row>

</el-drawer>

      <!-- 嵌套容器 -->
      <el-container>
        <!-- 侧边导航菜单 -->
        <!-- <el-aside width="150px"></el-aside> -->
        <!-- 内容 -->
        <el-main>
          <!-- 第一列栅格布局 -->
          <el-row>
            <el-col :span="12" class="col2">
               <el-table :data="allGRRKeys" ref="multipleTable" 
                v-el-table-infinite-scroll="load" highlight-current-row border @current-change="handleCurrentChange"
                height="300px">
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                ></el-table-column>
                <el-table-column prop="KEY" label="Item Name"></el-table-column>
              </el-table>             
            </el-col>
            
          </el-row>
          <!-- 第二列布局 -->
          <el-row>
            <el-col :span="12" class="col3">
              <!-- 导出csv -->
              <!-- 创建隐藏file input -->
              <input
                type="file"
                id="files"
                ref="refFile"
                v-on:change="importCsv"
                style="opacity: 0"
              />
              <input
                type="file"
                id="refs2"
                ref="refFile2"
                v-on:change="importGrr"
                style="opacity: 0"
              />
              <div class="titlestyle">SN分组:{{title}}</div>


               <div id="myChart" :style="{ height: '400px'  }"></div>
            </el-col>
             <el-col :span="12" class="Chart2">
                 <div class="titlestyle2">Station分组:{{title}}</div>

                 <div id="myChart2" :style="{ height: '400px' ,top:'30px' }"></div>
                           

             </el-col>
          </el-row>



        </el-main>
      </el-container>
      <!-- 底栏 -->
      <el-footer height="30px">&copy;HWTE</el-footer>
    </el-container>
  </div>
</template>

<script>
import Papa from "papaparse";
import elTableInfiniteScroll from 'el-table-infinite-scroll'
var chartManager;
var chartManager2;

export default {
  name: "HelloWorld",
  directives: {
    'el-table-infinite-scroll': elTableInfiniteScroll
  },
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      drawer: false,
      direction: 'ltr',
      clientHeight:'',
      allData:[],
      allBeginData:[],
      allItem:[],
    allStation:[],

      allGRRKeys:[],
      chatData:[],
      endLindata:[],
      multipleSelection: [],
      currentRow: null,
      title: "",
      itemList: [
        {
          name: "a",
          type: "P000001",
          price: "￥88888",
        },
        {
          name: "b",
          type: "P000002",
          price: "￥2000",
        },
      ]
    };
  },
  mounted() {
// 获取浏览器可视区域高度
      this.clientHeight =   `${document.documentElement.clientHeight}`          //document.body.clientWidth;
      //console.log(self.clientHeight);
      window.onresize = function temp() {
        this.clientHeight = `${document.documentElement.clientHeight}`;
      };
},
watch: {
      // 如果 `clientHeight` 发生改变，这个函数就会运行
      clientHeight: function () {
        this.changeFixed(this.clientHeight)
      }
    },

  methods: {
    handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      // handleClose(key, keyPath) {
      //   console.log(key, keyPath);
      // },
    clickMenu(value){
      if(value=="1-1"){
        this.$router.push({path:'/',query:{}});
      }
      if(value=="1-2"){
        this.$router.push({path:'/VidioCpk',query:{}});
      }
      if(value=="2-1"){
        this.$router.push({path:'/BoxLink',query:{}});
      }
      if(value=="3-1"){
        this.$router.push({path:'/VidioCpk',query:{}});
      }
      if(value=="3-2"){
        this.$router.push({path:'/VidioCpk',query:{}});
      }
      console.log(value)
    },
    changeFixed(clientHeight){                        //动态修改样式
        console.log(clientHeight);
        this.$refs.homePage.style.height = clientHeight+'px';

      },

      load(){},
    //多选
    handleSelectionChange(val) {
      // console.log(333333333333333+val)
      // this.multipleSelection = val;
      console.log("888888888")

      this.SelectFinish();

    },
    //单选
    handleCurrentChange(val) {


        this.title = val.ItemName;
        console.log(val.ItemName)
        this.currentRow = val;
        this.SelectFinish();




    },
    importGrr() {
        // alert(111)
      console.log('++++++++')
      let selectedFile = null;
      selectedFile = this.$refs.refFile2.files[0];
        console.log(selectedFile)

      if (selectedFile === undefined) {
        console.log('++111111++++++')

        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = (evt) => {
                  console.log('++222++++++')

        // 检查编码
        Papa.parse(selectedFile, {
          encoding: "ANSI",
          complete: (res) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;

            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            // this.allData = data;
            var KeyArr=[];
            for(var i=0;i<data.length;i++){
                var arr=data[i];
                for(var j=0;j<arr.length;j++){
                    var str=arr[j];
                    if(str.indexOf("KEY")!=-1){
                        KeyArr.push({"KEY":str.slice(7,-1)}) ;
                    }
    
                }
            }
            this.allGRRKeys=KeyArr;
            this.VidioBrokeline();
          },
        });
      };
    },
    importCsv() {
    //    this.drawLine()
    
      console.log('++++++++')
      let selectedFile = null;
      selectedFile = this.$refs.refFile.files[0];
      if (selectedFile === undefined) {
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = (evt) => {
        // 检查编码
        // let encoding = this.checkEncoding(evt.target.result);
        // 将csv转换成二维数组
        Papa.parse(selectedFile, {
          encoding: "ANSI",
          complete: (res) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;
            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            this.allData = data;
            this.allBeginData=data;
            this.VidioBrokeline();
          },
        });
      };
    },
    VidioBrokeline() {
    if(this.allGRRKeys.length>0&&this.allData.length>0){

    
      var datas = [];
      let first = this.allData[1];
      var headers = first;
        // console.log(this.allData);  // data就是文件里面的数据

      for (var i = 7; i < this.allData.length; i++) {
        var datal = {};
        var temp = this.allData[i];
        for (var j = 0; j < temp.length; j++) {
          datal[headers[j]] = temp[j];
        }
        if (datal.Site != "") {
          datas.push(datal);
        }
      }
    //   console.log(datas);  // data就是文件里面的数据
      this.allData = datas;
      const items = new Set();
        const stations = new Set();

    //   var station='Station ID';
      for(var i=0;i<this.allData.length;i++){
        var str=this.allData[i].SerialNumber
        var station=this.allData[i]["Station ID"]
        items.add(str) ;
        stations.add(station) ;

      }
      this.allItem =Array.from(items)  ;
        this.allStation =Array.from(stations)  ;

      this.SelectFinish();
    }
    },


  SelectFinish() {

    // this.currentRow="Audio Audio Output AMP-FINAL-TAMP"
    console.log("34343434")
        console.log(this.currentRow)
    this.title=this.currentRow["KEY"];

    var name=this.currentRow['KEY'];
    if(name!=null){
    var drwList={};
        var sList={};

    for(var j=0;j<this.allItem.length;j++){
        var snList=[];
        var stationList=[];

        for (var i = 0; i < this.allData.length; i++) {
           var list=this.allData[i];
        if (list.SerialNumber==this.allItem[j]){
                        // console.log(list[name])

               snList.push(list[name])
            }

         }
        drwList[this.allItem[j]]=snList;
    }
    for(var j=0;j<this.allStation.length;j++){
        var stationList=[];
        var Station="Station ID";
        for (var i = 0; i < this.allData.length; i++) {
           var list=this.allData[i];
        if (list[Station]==this.allStation[j]){
                        // console.log(list[name])

               stationList.push(list[name])
            }

         }
        sList[this.allStation[j]]=stationList;
    }
      this.drawLine( drwList,sList);
    }

  },
    drawLine(valueDataList,sList) {
        console.log("8989898989898989")
        console.log(valueDataList)
        console.log(sList)
        // sList=valueDataList;

      if (chartManager != null && chartManager != "" && chartManager != undefined){
        chartManager.dispose();
      }
      chartManager = this.$echarts.init(document.getElementById("myChart"));
                //随着屏幕大小调节图表
          window.addEventListener("resize", () => {
          chartManager.resize();
        });

        var keys=Object.keys(valueDataList);


        var firstAr=[];
        for (var i = 0; i < Object.values(valueDataList).length; i++) {
          var the=Object.values(valueDataList)[i]            
          for(var j=0;j<the.length;j++){
                firstAr.push(the[j])
          }

         }

        var  maxl = Math.max.apply(null, firstAr);
        var  minl = Math.min.apply(null, firstAr);


        var secondtAr=[];
        for (var i = 0; i < Object.values(sList).length; i++) {
          var the=Object.values(sList)[i]            
          for(var j=0;j<the.length;j++){
                secondtAr.push(the[j])
          }

         }

        var  maxT = Math.max.apply(null, secondtAr);
        var  minT = Math.min.apply(null, secondtAr);


        var zhongwei1
        let args=[...firstAr]; //收集参数转为数组

        args.sort() //排序
        console.log(args)

        if(firstAr.length%2===0){ //判断数字个数是奇数还是偶数
            var a=(args[args.length/2])
             var b=(args[args.length/2-1])
             a=Number(a);
             b=Number(b);
            zhongwei1=(a+b)/2;//偶数个取中间两个数的平均数
            console.log(zhongwei1)

        }else{
            zhongwei1=[parseInt(args.length/2)];//奇数个取最中间那个数
        }

      console.log(zhongwei1)



        var zhongwei2
        let args2=[...secondtAr]; //收集参数转为数组

        args2.sort() //排序
        console.log(args2)

        if(secondtAr.length%2===0){ //判断数字个数是奇数还是偶数
            var a=(args2[args2.length/2])
             var b=(args2[args2.length/2-1])
             a=Number(a);
             b=Number(b);
            zhongwei2=(a+b)/2;//偶数个取中间两个数的平均数
            console.log(zhongwei2)

        }else{
            zhongwei2=[parseInt(args2.length/2)];//奇数个取最中间那个数
        }

      console.log(zhongwei2)

      // 绘制图表
      chartManager.setOption({
        dataset: [
            {
            // prettier-ignore
            source: Object.values(valueDataList)
            },
            {
            transform: {
                type: 'boxplot',

            }
            },
            {
            fromDatasetIndex: 1,
            fromTransformResult: 1
            }
        ],

        tooltip: {
            trigger: 'item',
            axisPointer: {
            type: 'shadow'
            }
        },
        grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            boundaryGap: true,
            nameGap: 30,
            splitArea: {
            show: false
            },
            splitLine: {
            show: false
            },
            axisLabel: {
              // rotate:10,
              // align: center,
             formatter: function (value, index) {
                  var  params
                  var arr=Object.keys(valueDataList);
                  for (var i = 0; i < arr.length; i++) {
                    if(value==i){

                        params= Object.keys(valueDataList)[i] ;
                    }

                  }

      


                            var newParamsName = "";// 最终拼接成的字符串
                            var paramsNameNumber = params.length;// 实际标签的个数
                            var provideNumber = 12;// 每行能显示的字的个数
                            var rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
                            /**
                             * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
                             */
                            // 条件等同于rowNumber>1
                            if (paramsNameNumber > provideNumber) {
                                /** 循环每一行,p表示行 */
                                for (var p = 0; p < rowNumber; p++) {
                                    var tempStr = "";// 表示每一次截取的字符串
                                    var start = p * provideNumber;// 开始截取的位置
                                    var end = start + provideNumber;// 结束截取的位置
                                    // 此处特殊处理最后一行的索引值
                                    if (p == rowNumber - 1) {
                                        // 最后一次不换行
                                        tempStr = params.substring(start, paramsNameNumber);
                                    } else {
                                        // 每一次拼接字符串并换行
                                        tempStr = params.substring(start, end) + "\n";
                                    }
                                    newParamsName += tempStr;// 最终拼成的字符串
                                }

                            } else {
                                // 将旧标签的值赋给新标签
                                newParamsName = params;
                            }
                            //将最终的字符串返回
                            return newParamsName
                









              }

              
            }
        },
        yAxis: {
            type: 'value',
            name: 'value',
            splitArea: {
            show: true
            },
            min: minl,
            max: maxl,

        },
        series: [
            {
            name: 'boxplot',
            type: 'boxplot',
            datasetIndex: 1,
            markLine : {
                symbol:"none",
            
                           /*symbol:"none",               //去掉警戒线最后面的箭头
                           label:{
                               position:"end"   ,       //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                            
                            
                           },*/
                           data : [{
                                
                               silent:false,             //鼠标悬停事件  true没有，false有
                               lineStyle:{               //警戒线的样式  ，虚实  颜色
                                   type:"dashed",
                                   color:"#FA3934",
                               },
                                   label:{
                                   position:'end',
                                   formatter:"median"
                               },
                               yAxis:zhongwei1         // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                              
                           }

                           ]
          },
            },

            {
            name: 'outlier',
            type: 'scatter',
            datasetIndex: 2
            },
            
        ]
      });







    if (chartManager2 != null && chartManager2 != "" && chartManager2 != undefined){
        chartManager2.dispose();
      }
      chartManager2 = this.$echarts.init(document.getElementById("myChart2"));
                //随着屏幕大小调节图表
          window.addEventListener("resize", () => {
          chartManager2.resize();
        });



      // 绘制图表
      chartManager2.setOption({
  
        dataset: [
            {
            // prettier-ignore
            source: Object.values(sList)
            
            },
            {
            transform: {
                type: 'boxplot',
                // config: { itemNameFormatter: 'Station:{value}' }
            }
            },
            {
            fromDatasetIndex: 1,
            fromTransformResult: 1
            }
        ],

        tooltip: {
            trigger: 'item',
            axisPointer: {
            type: 'shadow'
            }
        },
        grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            boundaryGap: true,
            nameGap: 30,
            splitArea: {
            show: false
            },
            splitLine: {
            show: false
            },
            axisLabel: {
              // rotate:10,
              // align: center,
             formatter: function (value, index) {

              var  params
                  var arr=Object.keys(sList);
                  for (var i = 0; i < arr.length; i++) {
                    if(value==i){

                        params= Object.keys(sList)[i] ;
                    }

                  }

                            var newParamsName = "";// 最终拼接成的字符串
                            var paramsNameNumber = params.length;// 实际标签的个数
                            var provideNumber = 12;// 每行能显示的字的个数
                            var rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
                            /**
                             * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
                             */
                            // 条件等同于rowNumber>1
                            if (paramsNameNumber > provideNumber) {
                                /** 循环每一行,p表示行 */
                                for (var p = 0; p < rowNumber; p++) {
                                    var tempStr = "";// 表示每一次截取的字符串
                                    var start = p * provideNumber;// 开始截取的位置
                                    var end = start + provideNumber;// 结束截取的位置
                                    // 此处特殊处理最后一行的索引值
                                    if (p == rowNumber - 1) {
                                        // 最后一次不换行
                                        tempStr = params.substring(start, paramsNameNumber);
                                    } else {
                                        // 每一次拼接字符串并换行
                                        tempStr = params.substring(start, end) + "\n";
                                    }
                                    newParamsName += tempStr;// 最终拼成的字符串
                                }

                            } else {
                                // 将旧标签的值赋给新标签
                                newParamsName = params;
                            }
                            //将最终的字符串返回
                            return newParamsName
                
              }

              
            }
        },
        yAxis: {
            type: 'value',
            name: 'value',
            min: minT,
            max: maxT,
        },
        series: [
            {
            name: 'boxplot',
            type: 'boxplot',
            datasetIndex: 1,
            markLine : {
                symbol:"none",
            
                           /*symbol:"none",               //去掉警戒线最后面的箭头
                           label:{
                               position:"end"   ,       //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                            
                            
                           },*/
                           data : [{
                                
                               silent:false,             //鼠标悬停事件  true没有，false有
                               lineStyle:{               //警戒线的样式  ，虚实  颜色
                                   type:"dashed",
                                   color:"#FA3934",
                               },
                                   label:{
                                   position:'end',
                                   formatter:"median"
                               },
                               yAxis:zhongwei2         // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                              
                           }

                           ]
          },
            },
            {
            name: 'outlier',
            type: 'scatter',
            datasetIndex: 2
            },
            //  {
            // datasetIndex: 1,
            // type: 'line'
            //  }
        ]
      });





    },
    
    FuncCSVInport() {
      // 使用vue的ref参数直接操作input的点击事件触发 importCsv
      this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
    },
    FuncCSVInportTwo() {
      // 使用vue的ref参数直接操作input的点击事件触发 importCsv
      this.$refs.refFile2.dispatchEvent(new MouseEvent("click"));
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.el-header {
  background-color: #409eff;
  color: white;
  display:flex;
  text-align: left;
	flex-direction: column;
	justify-content: space-between;
}

.el-main{
  padding: 0px;
}
.el-footer {
  background-color: #909399;
  color: black;
  text-align: center;
}
.el-aside {
  background-color: chartreuse;
}
.el-main {
  background-color: rgb(215, 233, 207);;
}
.el-col {
  height: 300px;
}
.titlestyle{
  margin-bottom: 20px;
}
.titlestyle2{
  margin-top: 20px;
}
.col1 {
  background-color: rgb(36, 128, 0);
  height: 45%;
}
.col2 {
  background-color: tomato;
  height: 40%;
  width: 100%;
}
.col3 {
  background-color: rgb(215, 233, 207);
  height: 45%;
}
.Chart2 {
  background-color: rgb(215, 233, 207);
height: 50%;
}
.ImportButton{
}

</style>
